package com.zlyx.easy.core.utils;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.zlyx.easy.core.map.EasyMap;
import com.zlyx.easy.core.map.Maps;
import com.zlyx.easy.core.map.MultiMap;

public final class RequestUtils {

	public static final String UNKNOWN_IP = "unknown";

	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || UNKNOWN_IP.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN_IP.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN_IP.equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN_IP.equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN_IP.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static String getIp() {
		String ip = getIpAddress(getRequest());
		if (StringUtils.isNotEmpty(ip)) {
			return ip.split(",")[0];
		}
		return null;
	}

	public static String getHost() {
		return getRequest().getRequestURL().toString().replace(getRequest().getRequestURI(), "/");
	}

	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	public static Map<String, String[]> getParameterMap() {
		return getRequest().getParameterMap();
	}

	public static EasyMap<String, Object> getParamsMap() {
		Map<String, String[]> arraysMap = getRequest().getParameterMap();
		EasyMap<String, Object> params = Maps.newMap();
		String[] values = null;
		for (String name : arraysMap.keySet()) {
			values = arraysMap.get(name);
			if (ObjectUtils.isNotEmpty(values)) {
				params.put(name, values[0]);
			}
		}
		return params;
	}

	/**
	 * 
	 * @return
	 */
	public static MultiMap<String> getParamsTableMap() {
		Map<String, String[]> arraysMap = getRequest().getParameterMap();
		MultiMap<String> tableMap = MultiMap.newMap();
		String[] values = null;
		for (String name : arraysMap.keySet()) {
			values = arraysMap.get(name);
			if (ObjectUtils.isNotEmpty(values)) {
				tableMap.addValues(name, values);
			}
		}
		return tableMap;
	}

	public static String getClient() {
		return "http://" + getIp() + ":" + getRequest().getRemotePort();
	}
}
